package com.wangfei.xmljiexi;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class XmlExceutor {
//    @Test
//    public static void dom4j() {
//        //1.创建Reader对象
//        SAXReader reader = new SAXReader();
//        //2.加载xml
//        Document document = reader.read(new File("src/main/resources/demo.xml"));
//        //3.获取根节点
//        Element rootElement = document.getRootElement();
//        Iterator iterator = rootElement.elementIterator();
//        while (iterator.hasNext()){
//            Element stu = (Element) iterator.next();
//            List<Attribute> attributes = stu.attributes();
//            System.out.println("======获取属性值======");
//            for (Attribute attribute : attributes) {
//                System.out.println(attribute.getValue());
//            }
//            System.out.println("======遍历子节点======");
//            Iterator iterator1 = stu.elementIterator();
//            while (iterator1.hasNext()){
//                Element stuChild = (Element) iterator1.next();
//                System.out.println("节点名："+stuChild.getName()+"---节点值："+stuChild.getStringValue());
//            }
//        }
//    }

    public static void main(String[] args ) throws FileNotFoundException {
        // 1. 创建SAXBuilder对象
        SAXBuilder saxBuilder = new SAXBuilder();
        // 2. 配置xml文件名
        String fileName = "/Users/wangfei/Downloads/记录/wldmz/authority/ServiceAuthority.saf";
        //3.将输入流加载到build中
        Document document = null;
        LinkedHashMap<String, String> temMap = new LinkedHashMap<>();

        try {
            document = saxBuilder.build(fileName);
            //4.获取根节点
            Element rootElement = document.getRootElement();
            //5.获取子节点
            List<Element> children = rootElement.getChildren();
            returnMap(rootElement, temMap);
            System.out.println(temMap);

            System.out.println(temMap.get("Mappings").length());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        String test = "";
    }
    public static void returnMap(Element ele, Map outmap) {
        LinkedHashMap innermap = new LinkedHashMap();
        if (ele.getChildren().size() < 1 ) {
            List attrList = ele.getAttributes();
            attrList.forEach(childAttr -> outmap.put(ele.getName(), ele.getAttributes()));
        }
        List<Element> list = ele.getChildren();
        list.forEach(chaildElemnet -> returnMap(chaildElemnet, innermap));
        outmap.put(ele.getName(), innermap);

    }

}
